﻿namespace BEGDC.CC.Web.EZVisit.Controls
{
    #region Using Directives

    using System;
    using System.Linq;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using ASBCC.Database.Entity;
    using ASBCC.Database.Service;
    using BL.CCFlow;
    using BL.Common;
    using UserControls;
    using Utility.Castle;
    using Utility.Extensions;

    #endregion

    public partial class EZVRequestVisit : EZVRequestBaseControl
    {
        private decimal MaxGiftUnitPrice
        {
            get
            {
                decimal price;

                if (this.ViewState["MaxGiftUnitPrice"] == null)
                {
                    var utilityService = (IUtility)AppContainer.Instance[ServiceConst.UtilityService];

                    var dicItem = utilityService.GetDicItem("GiftUnitPrice", "GiftUnitPrice");

                    price = decimal.Parse(dicItem.Description);

                    this.ViewState["MaxGiftUnitPrice"] = price;
                }
                else
                {
                    price = decimal.Parse(this.ViewState["MaxGiftUnitPrice"].ToString());
                }

                return price;
            }
        }

        private DateTime CalendarWorkDays8
        {
            get
            {
                DateTime workdays8;

                if (this.ViewState["CalendarWorkDays8"] == null)
                {
                    string cnd = " Term > GETDATE() and xType = 0 order by Term";
                    aCalendarTableEntitySet set = aCalendarManager.SelectByCondition(cnd);
                    if (set.Count > 7)
                        workdays8 = set[7].Term.Value;
                    else
                        workdays8 = DateTime.Now.AddDays(9);
                    this.ViewState["CalendarWorkDays8"] = workdays8;
                }
                else
                {
                    workdays8 = DateTime.Parse(this.ViewState["CalendarWorkDays8"].ToString());
                }

                return workdays8;
            }
        }

        private bool IsDomestic
        {
            get
            {
                return DicType.Domestic.VariantEquals(this.Request.QueryString["Site"]);
            }
        }

        protected override void PreRenderPartialView()
        {
            
            this.SetVisibility();
            this.SetViewData();
        }

        protected override void SetVisibility()
        {
            base.SetVisibility();

            // Set actions
            this.dgInvitation.Columns[4].Visible = this.Editable;

            if (this.EZVisitApplication == null)
            {
                return;
            }

            if (CheckUrgentTime())
            {
                this.secUrgent1.Attributes.CssStyle["display"] = "block";
                this.edt_rfwUrgent.Enabled = true;

            }
            this.secGift1.Visible = this.secGift2.Visible = this.EZVisitApplication.IsNeedGift == null || this.EZVisitApplication.IsNeedGift.Value;
            if (this.EZVisitApplication.IsNeedEntertainment == null)
            {
                this.secEnt1.Visible = this.secEnt2.Visible = false;
            }
            else
            {
                this.secEnt1.Visible = this.secEnt2.Visible = this.EZVisitApplication.IsNeedEntertainment.Value;
            }
            this.secProvider.Visible = this.EZVisitApplication.CODPPManagerDate != null;
        }

        protected override void SetViewData()
        {
            if (this.EZVisitApplication == null)
            {
                return;
            }

            // In case new application
            if (this.EZVisitApplication.IsDomestic == null)
            {
                this.EZVisitApplication.IsDomestic = this.IsDomestic;
            }

            string startDate = this.EZVisitApplication.RequestedDateFrom != null ? this.EZVisitApplication.RequestedDateFrom.Value.ToString("MM/dd/yyyy") : string.Empty;
            string altStartDate = this.EZVisitApplication.AlternateDateFrom != null ? this.EZVisitApplication.AlternateDateFrom.Value.ToString("MM/dd/yyyy") : string.Empty;
            string endDate = this.EZVisitApplication.RequestedDateTo != null ? this.EZVisitApplication.RequestedDateTo.Value.ToString("MM/dd/yyyy") : string.Empty;
            string altEndDate = this.EZVisitApplication.AlternateDateTo != null ? this.EZVisitApplication.AlternateDateTo.Value.ToString("MM/dd/yyyy") : string.Empty;

            if (this.Editable)
            {
                this.edt_VisitStartDate.Text = startDate;
                this.edt_VisitEndDate.Text = endDate;
                this.edt_AltStartDate.Text = altStartDate;
                this.edt_AltEndDate.Text = altEndDate;
                this.edt_urgentCase.Text = this.EZVisitApplication.UrgentCaseComments != null ? this.EZVisitApplication.UrgentCaseComments : string.Empty;

                this.edt_OtherPlaces.Text = this.EZVisitApplication.OtherSite;
                this.edt_VisitReason.Text = this.EZVisitApplication.ReasonOfLocation;
                this.edt_Cities.Text = this.EZVisitApplication.VisitCity;
                //Gift
                this.edt_GiftsNeeded.SelectedValue = this.EZVisitApplication.IsNeedGift != null && !this.EZVisitApplication.IsNeedGift.Value ? "0" : "1";  
                this.edt_GiftDescription.Text = this.EZVisitApplication.GiftDesc;
                this.edt_GiftPrice.Text = this.EZVisitApplication.GiftUnitPrice.GetValueOrDefault(this.MaxGiftUnitPrice).ToString();
                this.edt_GiftCount.Text = this.EZVisitApplication.GiftAmount.GetValueOrDefault(1).ToString();
                this.edt_CalendarWorkDays8.Text = this.EZVisitApplication.SubmitDate.GetValueOrDefault(this.CalendarWorkDays8).ToString("MM/dd/yyyy");
                //Entertainment
                this.edt_EntNeeded.SelectedValue = this.EZVisitApplication.IsNeedEntertainment == null || !this.EZVisitApplication.IsNeedEntertainment.Value ? "0" : "1";
                this.edt_EntDescription.Text = this.EZVisitApplication.EntertainmentPreference;
                this.edt_EntFromPrice.Text = this.EZVisitApplication.EntertainmentPriceFrom != null ? this.EZVisitApplication.EntertainmentPriceFrom.ToString() : string.Empty;
                this.edt_EntToPrice.Text = this.EZVisitApplication.EntertainmentPriceTo != null ? this.EZVisitApplication.EntertainmentPriceTo.ToString() : string.Empty;

                this.edt_InvitationProvided.SelectedValue = this.EZVisitApplication.IsNeedInvitationLetter != null && !this.EZVisitApplication.IsNeedInvitationLetter.Value ? "0" : "1";

                this.edt_cv3.ValueToCompare = this.MaxGiftUnitPrice.ToString();
                this.edt_cv3.ErrorMessage = string.Format("[Visit Info.] Gifts price should be less than or equal to {0}.", this.MaxGiftUnitPrice);
                // this.edt_cmp.ErrorMessage = string.Format("[Visit Info.] Visit start date should be greater than {0}.", this.CalendarWorkDays8.ToString("MM/dd/yyyy"));


                this.BindVisitPlaces();
            }
            else
            {
                this.vw_VisitStartDate.Text = startDate;
                this.vw_VisitEndDate.Text = endDate;
                this.vw_urgentCase.Text = this.EZVisitApplication.UrgentCaseComments != null ? this.EZVisitApplication.UrgentCaseComments : string.Empty;
                if (altStartDate.Length != 0)
                {
                    this.vw_AltStartDate.Text = "From " + altStartDate;
                    this.vw_AltEndDate.Text = " To " + altEndDate;
                }
                else
                {
                    this.secVisit1.Visible = false;
                }
                //Gift
                this.vw_GiftDescription.Text = this.EZVisitApplication.GiftDesc;
                this.vw_GiftPrice.Text = this.EZVisitApplication.GiftUnitPrice.GetValueOrDefault(0).ToString();
                this.vw_GiftCount.Text = this.EZVisitApplication.GiftAmount.GetValueOrDefault(0).ToString();
                //Entermainment
                this.vw_EntDescription.Text = this.EZVisitApplication.EntertainmentPreference;
                this.vw_EntFromPrice.Text = this.EZVisitApplication.EntertainmentPriceFrom.GetValueOrDefault().ToString();
                this.vw_EntToPrice.Text = this.EZVisitApplication.EntertainmentPriceTo.GetValueOrDefault().ToString();

                this.vw_VisitPlaces.Text = this.EZVisitApplication.IsDomestic.Value ? this.EZVisitApplication.DomesticDesc : this.EZVisitApplication.OverseaDesc;
                this.vw_OtherPlaces.Text = this.EZVisitApplication.OtherSite;
                this.vw_Cities.Text = this.EZVisitApplication.VisitCity;

                this.vw_VisitReason.Text = this.EZVisitApplication.ReasonOfLocation;
                this.vw_GiftsNeeded.Text = this.EZVisitApplication.IsNeedGift != null && !this.EZVisitApplication.IsNeedGift.Value ? "No" : "Yes";
                this.vw_EntNeeded.Text = this.EZVisitApplication.IsNeedEntertainment != null && !this.EZVisitApplication.IsNeedEntertainment.Value ? "No" : "Yes";
                this.vw_InvitationProvided.Text = this.EZVisitApplication.IsNeedInvitationLetter != null && !this.EZVisitApplication.IsNeedInvitationLetter.Value ? "No" : "Yes";
            }

            this.lblGiftsValue.Text = this.EZVisitApplication.GiftTotalValue.GetValueOrDefault(1).ToString();

            this.lblInfo.Visible = this.Editable ? this.edt_InvitationProvided.SelectedValue.Equals("1") : this.vw_InvitationProvided.Text.Equals("Yes");

            if (this.EZVisitApplication.ProviderKey.IsNotNullOrWhiteSpace())
            {
                this.lblProvider.Text = this.EZVisitApplication.ProviderKey.VariantEquals("Others") ? this.EZVisitApplication.OthersProviderDesc : this.EZVisitApplication.ProviderDesc;
            }

            this.BindVisa();
        }

        protected override bool Validate(out string error)
        {
            error = string.Empty;

            if (this.CurrentActionType.IsNotNullOrWhiteSpace())
            {
                if (string.IsNullOrEmpty(this.edt_VisitPlaces.SelectedValue))
                {
                    error = @"- [Visit Info.] Preferred locations were not provided.\n";
                }

                if (this.edt_InvitationProvided.Visible && this.edt_InvitationProvided.SelectedValue.Equals("1") && this.dgInvitation.Items.Count == 0)
                {
                    error += @"- [Visit Info.] Visa attachment was not provided.\n";
                }

                if (this.edt_AltStartDate.Text.Trim().Length == 0 && this.edt_AltEndDate.Text.IsNotNullOrWhiteSpace())
                {
                    error += @"- [Visit Info.] Alternate visit start date cannot be empty when the end date was set.\n";
                }

                if (this.edt_AltEndDate.Text.Trim().Length == 0 && this.edt_AltStartDate.Text.IsNotNullOrWhiteSpace())
                {
                    error += @"- [Visit Info.] Alternate visit end date cannot be empty when the start date was set.\n";
                }
            }

            return error.Length == 0;
        }

        public override void Save(EZVisitApplicationTableEntity app)
        {
            if (app == null)
            {
                return;
            }

            if (app.IsDomestic == null)
            {
                app.IsDomestic = this.IsDomestic;
            }

            app.RequestedDateFrom = this.edt_VisitStartDate.Text.IsNotNullOrWhiteSpace() ? DateTime.Parse(this.edt_VisitStartDate.Text) : new DateTime?();
            app.RequestedDateTo = this.edt_VisitEndDate.Text.IsNotNullOrWhiteSpace() ? DateTime.Parse(this.edt_VisitEndDate.Text) : new DateTime?();

            app.AlternateDateFrom = new DateTime?();
            app.AlternateDateTo = new DateTime?();

            if (this.edt_urgentCase.Text.IsNotNullOrWhiteSpace())
            {
                if (this.urgentHidden.Value.IsNotNullOrWhiteSpace()&&int.Parse(this.urgentHidden.Value) <= 3)
                {

                    app.UrgentCaseComments = this.edt_urgentCase.Text;
                }
                else if (CheckUrgentTime())
                {
                    app.UrgentCaseComments = this.edt_urgentCase.Text;
                }
                else
                {
                    app.UrgentCaseComments = null;
                }

            }
            else
            {
                app.UrgentCaseComments = null;
            }

            if (this.edt_AltStartDate.Text.IsNotNullOrWhiteSpace())
            {
                DateTime d;

                if (DateTime.TryParse(this.edt_AltStartDate.Text, out d))
                {
                    app.AlternateDateFrom = d;
                }
            }

            if (this.edt_AltEndDate.Text.IsNotNullOrWhiteSpace())
            {
                DateTime d;

                if (DateTime.TryParse(this.edt_AltEndDate.Text, out d))
                {
                    app.AlternateDateTo = d;
                }
            }

            string selectedPlacesValue = string.Empty, selectedPlacesText = string.Empty;

            foreach (ListItem li in this.edt_VisitPlaces.Items.Cast<ListItem>().Where(li => li.Selected))
            {
                selectedPlacesValue += li.Value + ",";
                selectedPlacesText += li.Text + ",";
            }

            if (app.IsDomestic.Value)
            {
                app.DomesticList = selectedPlacesValue.TrimEnd(',');
                app.DomesticDesc = selectedPlacesText.TrimEnd(',');
            }
            else
            {
                app.OverseaList = selectedPlacesValue.TrimEnd(',');
                app.OverseaDesc = selectedPlacesText.TrimEnd(',');
            }

            app.OtherSite = this.edt_OtherPlaces.Text;
            app.VisitCity = this.edt_Cities.Text;
            app.ReasonOfLocation = this.edt_VisitReason.Text;

            if (this.secVisit.Visible)
            {
                app.IsNeedInvitationLetter = this.edt_InvitationProvided.SelectedValue.Equals("1");
            }

            bool needGift = this.edt_GiftsNeeded.SelectedValue.Equals("1");
            app.IsNeedGift = needGift;

            app.GiftDesc = needGift ? this.edt_GiftDescription.Text : string.Empty;

            decimal dGiftUnitPrice;
            int iGiftAmount;
            if (needGift)
            {
                decimal.TryParse(this.edt_GiftPrice.Text, out dGiftUnitPrice);
                app.GiftUnitPrice = dGiftUnitPrice;
                int.TryParse(this.edt_GiftCount.Text, out iGiftAmount);
                app.GiftAmount = iGiftAmount; 
            }
            else
            {
                app.GiftUnitPrice = 0;
                app.GiftAmount = 0;
            }

            app.GiftTotalValue = app.GiftAmount.Value * app.GiftUnitPrice.Value;

            bool needEntertainment = this.edt_EntNeeded.SelectedValue.Equals("1");
            app.IsNeedEntertainment = needEntertainment;
            decimal dEntertainmentPriceFrom;
            decimal dEntertainmentPriceTo;
            if (needEntertainment)
            {
                app.EntertainmentPreference = this.edt_EntDescription.Text;
                decimal.TryParse(this.edt_EntFromPrice.Text, out dEntertainmentPriceFrom);
                decimal.TryParse(this.edt_EntToPrice.Text, out dEntertainmentPriceTo);
                app.EntertainmentPriceFrom = dEntertainmentPriceFrom;
                app.EntertainmentPriceTo = dEntertainmentPriceTo;
            }
            else
            {
                app.EntertainmentPreference = null;
                app.EntertainmentPriceFrom = null;
                app.EntertainmentPriceTo = null;
            }

            base.Save(app);
            this.SaveVisa();
        }

        public void BindVisa()
        {
            if (this.EZVisitApplication == null || !this.Visible)
            {
                return;
            }

            if (this.EZVisitApplication.IsDomestic != null && this.EZVisitApplication.IsDomestic.Value)
            {
                this.secVisit.Visible = false;
                return;
            }

            if (this.EZVisitApplication.AppIDIsNull())
            {
                return;
            }

            var dt = this.GetAttachments(AttachmentType.VISA).OfType<UploadFileTableEntity>().ToDataTable();

            this.secVisa.Visible = this.dgInvitation.Visible = dt.Rows.Count > 0;
            this.edt_UploadInvitation.Visible = this.Editable & dt.Rows.Count == 0 & this.edt_InvitationProvided.SelectedValue.Equals("1");
            this.edt_InvitationTemplate.Visible = this.Editable & this.edt_InvitationProvided.SelectedValue.Equals("1");
            this.dgInvitation.DataSource = dt;
            this.dgInvitation.DataBind();
        }

        private void SaveVisa()
        {
            if (this.edt_InvitationProvided.SelectedValue.Equals("0") && this.dgInvitation.Items.Count > 0)
            {
                UploadFileManager.DeleteByCondition(string.Format("FileID={0}", this.dgInvitation.Items[0].Cells[0].Text));
                this.BindVisa();
            }
        }

        private void BindVisitPlaces()
        {
            WebUtility.BuildCheckBoxList(this.edt_VisitPlaces, this.EZVisitApplication.IsDomestic.Value ? DicType.Domestic : DicType.Oversea);

            var places = new string[0];

            if (this.EZVisitApplication.IsDomestic.Value && this.EZVisitApplication.DomesticList.IsNotNullOrWhiteSpace())
            {
                places = this.EZVisitApplication.DomesticList.Split(',');
            }
            else if (this.EZVisitApplication.OverseaList.IsNotNullOrWhiteSpace())
            {
                places = this.EZVisitApplication.OverseaList.Split(',');
            }

            foreach (var li in places.Select(place => this.edt_VisitPlaces.Items.FindByValue(place)).Where(li => li != null))
            {
                li.Selected = true;
            }
        }

        private UploadFileTableEntitySet GetAttachments(AttachmentType attachmentType)
        {
            string condition = string.Format("AppID={0} and IsEnabled=1 and AttachmentTypeKey='{1}' and AppType='EZV'", this.EZVisitApplication.AppID, attachmentType);

            return UploadFileManager.SelectByCondition(condition);
        }

        protected void rblInvitationProvided_SelectedIndexChanged(object sender, EventArgs e)
        {
            bool visible = this.edt_InvitationProvided.SelectedValue.Equals("1");

            this.edt_UploadInvitation.Visible = visible & this.dgInvitation.Items.Count == 0;

            this.lblInfo.Visible = this.edt_InvitationTemplate.Visible = visible;
            this.secVisa.Visible =  this.dgInvitation.Visible = this.dgInvitation.Items.Count > 0 && visible;
        }

        protected void rblGiftsNeeded_SelectedIndexChanged(object sender, EventArgs e)
        {
            bool visible = this.edt_GiftsNeeded.SelectedValue.Equals("1");

            this.secGift1.Visible = this.secGift2.Visible = visible;
        }

        protected void rblEntNeeded_SelectedIndexChanged(object sender, EventArgs e)
        {
            bool visible = this.edt_EntNeeded.SelectedValue.Equals("1");

            this.secEnt1.Visible = this.secEnt2.Visible = visible;
        }

        protected void dgInvitation_DeleteCommand(object source, DataGridCommandEventArgs e)
        {
            DeleteAttachement(Convert.ToInt32(e.Item.Cells[0].Text));

            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "reloadvisa", "reload('visa');", true);
        }

        protected void dgInvitation_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if ((e.Item.ItemType != ListItemType.Item) && (e.Item.ItemType != ListItemType.AlternatingItem))
            {
                return;
            }

            var cell = e.Item.Cells[4];

            var btnDelete = (ImageButton)cell.FindControl("btnDelete");
            btnDelete.Attributes.Add("onclick", "return confirm('Are you sure to delete this item?');");
        }

        private static void DeleteAttachement(int fileId)
        {
            var attachment = UploadFileManager.SelectByKeys(fileId);

            if (attachment == null)
            {
                return;
            }

            attachment.IsEnabled = false;
            UploadFileManager.Update(attachment);
        }

        private  bool CheckUrgentTime()
        {
            DateTime? visitStartDate = this.EZVisitApplication.RequestedDateFrom;
            if (visitStartDate.HasValue)
            {
                DateTime dt = new DateTime(visitStartDate.Value.Year, visitStartDate.Value.Month, visitStartDate.Value.Day);
                TimeSpan ts1 = new TimeSpan(dt.Ticks);
                TimeSpan ts2 = new TimeSpan(this.EZVisitApplication.CreateAt.GetValueOrDefault(DateTime.Now).Ticks);
                TimeSpan diff = ts1.Subtract(ts2);
                int diffDays = diff.Days;
                bool result= diffDays <= 3 ? true : false;
                return result;
            }

            return false;
        }
    }
}